﻿#include "responseutil.h"
#include <QBuffer>
#include <QFileInfo>

ResponseUtil::ResponseUtil()
{

}

void ResponseUtil::replyJson(HttpResponse& response, ResultJson result)
{
    response.setHeader("Content-Type", "application/json;charset:utf-8");
    response.setHeader("Cache-Control", "no-store");
    QString retStr = result.toString();
    response.write(retStr.toLocal8Bit());
}

void ResponseUtil::replyString(HttpResponse& response, QString result)
{
    response.setHeader("Content-Type", "text/xml;charset=utf-8");
    response.setHeader("Cache-Control", "no-store");
    response.write(result.toLocal8Bit());
}

void ResponseUtil::replyImage(HttpResponse& response, QImage &image)
{
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    image.save(&buffer, "PNG");

    response.setHeader("Content-Type", "image/png");
    response.write(buffer.data());
}

void ResponseUtil::replyHtml(HttpResponse& response, QString result)
{

}

void ResponseUtil::replyFile(HttpResponse& response, QString fileName)
{
    QFileInfo info(fileName);
    QFile localFile(fileName);
    if(!localFile.exists())
    {
        response.write("");
        return;
    }
    if(!localFile.open(QIODevice::ReadOnly))
    {
        response.write("");
        return;
    }

    QByteArray data = localFile.readAll();
    localFile.close();

    QString disposition = QString("attachment; filename=\"%1\"").arg(info.fileName());
    //设置下载的附件(filename必须处理中文名称)
    response.setHeader("Content-Disposition", disposition.toLocal8Bit());
    response.setHeader("Content-Type", "application/octet-stream");
    //缓存头Cache-Control
    //no-cache：不直接使用缓存，要求向服务器发起（新鲜度校验）请求
    //no-store：所有内容都不会被保存到缓存或Internet临时文件中
    //must-revalidate：当前资源一定是向原服务器发去验证请求的，若请求失败会返回504（而非代理服务器上的缓存）
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    //不要网页存于缓存之中
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "0");
    response.setHeader("Content-Length", data.length());

    response.write(data);
}
